package com.lalifa.googledate.util

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlarmManager
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.ActivityNotFoundException
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.media.MediaPlayer
import android.media.RingtoneManager
import android.os.Build
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import com.drake.net.utils.scopeNetLife
import com.hjq.widget.view.DrawableTextView
import com.lalifa.extension.onClick
import com.lalifa.extension.start
import com.lalifa.extension.toast
import com.lalifa.googledate.R
import com.lalifa.googledate.api.RemindBean
import com.lalifa.googledate.ui.activity.MainActivity
import per.goweii.layer.core.ktx.onInitialize
import per.goweii.layer.notification.NotificationLayer
import per.goweii.layer.notification.ktx.contentView
import java.io.IOException


// 创建一个通知渠道
fun Context.createNotificationChannel() {
    //if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val channelId = "my_channel_id"
        val channelName = "My Channel"
        val importance = NotificationManager.IMPORTANCE_HIGH
        val channel = NotificationChannel(channelId, channelName, importance)
        val notificationManager = getSystemService(NotificationManager::class.java)
        notificationManager.createNotificationChannel(channel)
   // }
}

// 发送带声音和震动的通知
@SuppressLint("MissingPermission")
fun Context.sendNotificationWithSoundAndVibration(
    id: String,
    title: String = "",
    text: String = ""
) {
    // 创建一个 PendingIntent，用于点击通知后启动应用程序
    val intent = Intent(this, MainActivity::class.java)
    intent.putExtra("id", id)
    intent.addCategory(Intent.CATEGORY_LAUNCHER)
    intent.component = ComponentName(this, MainActivity::class.java)
    intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
    val pendingIntent = if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.S)
        PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)
    else PendingIntent.getActivity(this, 0, intent, 0)
    val channelId = "my_channel_id"
    val notificationBuilder = NotificationCompat.Builder(this, channelId)
        .setSmallIcon(R.mipmap.icon_app)
        .setContentTitle(title)
        .setContentText(text)
        .setContentIntent(pendingIntent) // 设置点击通知后的操作
        .setAutoCancel(true) // 点击通知后自动取消通知
        .setFullScreenIntent(pendingIntent, true) // 设置通知为横幅通知
        .setPriority(NotificationCompat.PRIORITY_HIGH)
    (this as AppCompatActivity).scopeNetLife {
        notificationBuilder.setDefaults(NotificationCompat.DEFAULT_SOUND or NotificationCompat.DEFAULT_VIBRATE) // 添加声音和震动
            .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)) // 设置通知声音
        val notificationManager = NotificationManagerCompat.from(this@sendNotificationWithSoundAndVibration)
        notificationManager.notify(1, notificationBuilder.build())
    }


    // 获取振动器服务
//    val vibrator = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
//
//    // 创建震动模式（这里使用默认的震动模式）
//    val vibrationPattern = longArrayOf(0, 500, 100, 500)
//
//    // 检查 Android 版本，因为 Android Oreo（26）之后，震动模式有所不同
//    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//        val vibrationEffect = VibrationEffect.createWaveform(vibrationPattern, -1)
//        vibrator.vibrate(vibrationEffect)
//    } else {
//        vibrator.vibrate(vibrationPattern, -1)
//    }


}

fun Context.removeNotificationWithSoundAndVibration() {
    // 获取通知管理器
    val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

    // 传入要移除的通知的ID
    val notificationIdToRemove = 1  // 这里的 1 是通知的ID，你需要根据实际情况替换

    // 取消特定ID的通知
    notificationManager.cancel(notificationIdToRemove)
}

fun Context.sendWidthNotification(userId: String, title: String = "", text: String = "") {
    // 创建一个 PendingIntent，用于点击通知后启动应用程序
    val intent = Intent(this, MainActivity::class.java)
    intent.putExtra("id", userId)
    intent.addCategory(Intent.CATEGORY_LAUNCHER)
    intent.component = ComponentName(this, MainActivity::class.java)
    intent.flags =
        Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK or
                Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
    val pendingIntent = if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.S)
        PendingIntent.getActivity(this, 0, intent,  PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
    else PendingIntent.getActivity(this, 0, intent, 0)

    val channelId = "youxipeiwan"
    val channelName = "youxipeiwan"
    // 创建通知渠道（仅适用于 Android 8.0 及更高版本）
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val channel =
            NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH)
        val notificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.createNotificationChannel(channel)
    }

    // 构建横幅通知
    val builder = NotificationCompat.Builder(this, channelId)
        .setSmallIcon(R.mipmap.icon_app)
        .setContentTitle(title)
        .setContentText(text)
        .setContentIntent(pendingIntent) // 设置点击通知后的操作
        .setAutoCancel(true) // 点击通知后自动取消通知
        .setPriority(NotificationCompat.PRIORITY_HIGH)
        .setCategory(NotificationCompat.CATEGORY_MESSAGE) // 设置通知类型为消息
        .setFullScreenIntent(pendingIntent, true) // 设置通知为横幅通知
        .setTimeoutAfter(5000) // 设置通知存在时间为5秒

    // 显示横幅通知
    with(NotificationManagerCompat.from(this)) {
        if (ActivityCompat.checkSelfPermission(
                this@sendWidthNotification,
                Manifest.permission.POST_NOTIFICATIONS
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            return
        }
        notify(2, builder.build())
    }
}

fun Context.getAudioDuration(audioUrl: String, onDurationReceived: (Int) -> Unit) {
    val mediaPlayer = MediaPlayer()

    try {
        mediaPlayer.setDataSource(audioUrl)
        mediaPlayer.setOnPreparedListener { mp ->
            val duration = mp.duration // 获取音频时长，单位为毫秒
            val durationInSeconds = duration / 1000 // 转换为秒
            onDurationReceived(durationInSeconds)
            mp.release() // 释放 MediaPlayer 资源
        }

        mediaPlayer.setOnErrorListener { mp, what, extra ->
            // 处理错误
            mp.release()
            false
        }

        mediaPlayer.prepareAsync()
    } catch (e: IOException) {
        // 处理异常
        e.printStackTrace()
    }
}

/**
 * 消息通知气泡
 */
fun Activity.showNotificationLayer(bean:RemindBean) {
    NotificationLayer(this)
        .contentView(R.layout.notification_layout)
        .setDuration(5000)
        .onInitialize {
            requireViewById<DrawableTextView>(R.id.no_title).text = bean.title
            requireViewById<TextView>(R.id.no_content).text = bean.content
            requireViewById<RelativeLayout>(R.id.parent).onClick {
                start(MainActivity::class.java) {
                    putExtra("id", bean.id)
                }
                dismiss()
            }
            setAutoDismiss(true)
        }.show()
}


fun Context.launchActivityIntent(intent: Intent) {
    try {
        startActivity(intent)
    } catch (e: ActivityNotFoundException) {
        toast(R.string.no_app_found)
    } catch (e: Exception) {
        toast(e.toString())
    }
}

